<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { Button, Popconfirm } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { GroupApi } from '#/api/system/group';

import GroupForm from './group-form.vue';

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入查询关键字',
      },
      label: '关键字',
      defaultValue: '',
      fieldName: 'query',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
};
const gridOptions: VxeGridProps<GroupApi.GroupResult> = {
  columns: [
    { field: 'name', title: '名称' },
    { slots: { default: 'action' }, title: '操作', width: 150 },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) =>
        GroupApi.listGroup({
          page: page.currentPage,
          page_size: page.pageSize,
          ...formValues,
        }),
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
const [EditModal, editModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: GroupForm,
});

function openGroupForm(row?: GroupApi.GroupResult) {
  editModalApi.setData(row ?? {}).open();
}

async function createGroup(data: Partial<GroupApi.GroupResult>) {
  const row = await GroupApi.createGroup(data);
  gridApi.grid.insert(row);

  editModalApi.close();
}

async function updateGroup({ id, data }: { data: Partial<GroupApi.GroupResult>; id: string }) {
  const record = await GroupApi.updateGroup(id, data);
  const row = gridApi.grid.getRowById(id);
  gridApi.grid.setRow(row, record);
  editModalApi.close();
}

async function deleteGroup(row: GroupApi.GroupResult) {
  await GroupApi.deleteGroup(row.id);
  gridApi.grid.remove(row);
}
</script>

<template>
  <Page title="用户组">
    <Grid>
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="() => gridApi.query()"> 刷新 </Button>
      </template>
      <template #toolbar-actions>
        <Button type="primary" @click="openGroupForm()" title="新增用户"> 新增 </Button>
      </template>
      <template #action="{ row }">
        <Button type="link" @click="openGroupForm(row)" title="修改用户组">
          <IconifyIcon icon="fa6-solid:pen-to-square" />
        </Button>
        <Popconfirm @confirm="deleteGroup(row)" title="确认删除？">
          <Button type="link" danger title="删除用户组">
            <IconifyIcon icon="fa6-solid:trash" />
          </Button>
        </Popconfirm>
      </template>
    </Grid>
    <EditModal @create="createGroup" @update="updateGroup" />
  </Page>
</template>
